<?php

namespace app\modules\clinical\models;

use Yii;

/**
 * This is the model class for table "visit_medicine".
 *
 * @property integer $pk_id
 * @property integer $pt_id
 * @property string $ft_md_time
 * @property string $md_name
 * @property integer $md_amount
 * @property integer $md_times
 * @property string $md_usage
 * @property string $md_side_effect
 * @property string $crt_name
 * @property string $crt_time
 */
class VisitMedicine extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'visit_medicine';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['pt_id', 'ft_md_time', 'md_name', 'md_amount', 'md_times', 'md_usage', 'md_side_effect'], 'required'],
            [['pt_id', 'rel_id', 'md_times'], 'integer'],
            [['md_amount'], 'number'],
            [['ft_md_time', 'crt_time', 'update_at'], 'safe'],
            [['md_name'], 'string', 'max' => 50],
            [['md_usage', 'md_side_effect'], 'string', 'max' => 255],
            [['crt_name', 'update_name'], 'string', 'max' => 30]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'pk_id' => 'Pk ID',
            'pt_id' => 'Pt ID',
            'rel_id' => 'Rel ID',
            'ft_md_time' => '首次用药时间',
            'md_name' => '药物名称',
            'md_amount' => '单次剂量',
            'md_times' => '次数',
            'md_usage' => '用法',
            'md_side_effect' => '副作用',
            'crt_name' => '创建人',
            'crt_time' => '创建时间',
            'update_name' => '修改人',
            'update_at' => '修改时间',

            'ppt_id' => '病案号',
            'pt_name' => '患者姓名',
        ];
    }

    public function getPatient()
    {
        return $this->hasOne(Patient::className(), ['pk_id' => 'pt_id']);
    }

    public function beforeSave($insert)
    {
        if(parent::beforeSave($insert)){
            if($this->isNewRecord){

                $this->crt_time = date('y-m-d H:i:s');
                $this->crt_name = Yii::$app->user->identity->username;
            }else{
                $this->update_at = date('y-m-d H:i:s');
                $this->update_name = Yii::$app->user->identity->username;
            }
            return true;
        }else{

            return false;
        }
    }
}
